package com.kempca.moviecenter.io;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.io.FilenameFilter;

import com.kempca.moviecenter.model.Media;
import com.kempca.moviecenter.model.Movie;

public class MovieFileAccess {
	
	private final static String BASE_MOVIE_DIRECTORY = "Z:";
	
	public List<Media> loadAllMedia() throws Exception {
		
		File movieDirectory = new File(BASE_MOVIE_DIRECTORY);
		
		if (!movieDirectory.exists()) {
			throw new Exception("Base movie directory:  " + BASE_MOVIE_DIRECTORY + " does not exist");
		}
		
		if (!movieDirectory.isDirectory()) {
			throw new Exception("Base movie directory:  " + BASE_MOVIE_DIRECTORY + " is not a directory");
		}
		
		File[] movieArray = movieDirectory.listFiles(getFileNameFilter());
		
		List<Media> media = new ArrayList<Media>();
		
		for (int i = 0; i < movieArray.length; i++) {
			File movieFile = movieArray[i];
			Media movie = new Movie(getMovieName(movieFile.getPath()), movieFile.getPath());
			media.add(movie);
		}
		
		return media;
	}
	
	
	public String getMovieName(String path) {
		path = path.substring(path.indexOf(BASE_MOVIE_DIRECTORY) + BASE_MOVIE_DIRECTORY.length() + 1, path.length());
		path = path.substring(0, path.length() - 4);
		return path;
	}
	
	
	public FilenameFilter getFileNameFilter() {
		
		FilenameFilter fnf = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				String lowercaseName = name.toLowerCase();
				if (lowercaseName.endsWith(".iso")) {
					return true;
				} else {
					return false;
				}
			}
		};
		
		return fnf;
	}

}
